package com.robotserver.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.constant.CacheKey;
import com.robotserver.orders.entity.AlimmTokens;
import com.robotserver.orders.entity.JdTokens;
import com.robotserver.orders.mapper.AlimmTokensMapper;
import com.robotserver.orders.mapper.JdTokensMapper;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.param.JdOrderSyncParam;
import com.robotserver.orders.param.PddOrderSyncParam;
import com.robotserver.orders.param.TbOrderSyncParam;
import com.robotserver.orders.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2020/4/26 14:44
 * @Description:
 */
@Service
public class ListenTokenRunServiceImpl implements ListenTokenRunService {

    private Logger logger = LoggerFactory.getLogger(ListenTokenRunServiceImpl.class);

    @Autowired
    private JdTokensMapper jdTokensMapper;
    @Autowired
    private AlimmTokensMapper alimmTokensMapper;
    @Autowired
    private JdOrderService jdOrderService;
    @Autowired
    private TbOrderService tbOrderService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private PddOrderService pddOrderService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void listen() {

        logger.info("---------根据心跳检测各平台拉取订单运行情况------开始------");

        // 获取
        int now = DateUtil.getNowTime();
        int lasttime = now-120;
        int validTime = now-172800; // 两天内修改的token都需要同步
        int runTime = now - 300;
        String content = "";

        /**  京东更新联盟订单，由于京东已经采用工具商获取订单，故屏蔽
        int jdlasttime = lasttime-60;
        List<JdTokens> jdTokens = jdTokensMapper.getNotRunToken(validTime,jdlasttime);
        if (jdTokens!=null && jdTokens.size()>0){
            logger.info("not run jd token:{}",jdTokens);
            content = "京东token:"+jdTokens;

            for (JdTokens token:jdTokens){
                JdOrderSyncParam syncParam = new JdOrderSyncParam();
                syncParam.setUnionId(token.getUnionId());
                syncParam.setAuthKey(token.getAuthKey());
                syncParam.setBegin_time((long)runTime);
                syncParam.setEnd_time((long)now);
                syncParam.setTokenId(token.getId());
                syncParam.setType(token.getType());

                jdOrderService.syncOrder(syncParam);
            }
        }
        **/


        //根据心跳拉取淘宝联盟订单
        List<AlimmTokens> alimmTokens = alimmTokensMapper.getNotRunToken(validTime,lasttime);
        if (alimmTokens!=null && alimmTokens.size()>0){
            logger.info("not run tb token:{}",alimmTokens);
            content = content + ",淘宝token:"+alimmTokens;

            for (AlimmTokens token:alimmTokens){
                /**旧版的方法，已经成新的方法，插入到redis当中
                TbOrderSyncParam syncParam = new TbOrderSyncParam();
                syncParam.setBegin_time((long)runTime);
                syncParam.setEnd_time((long)now);
                syncParam.setUserId(token.getUserId());
                syncParam.setUserName(token.getUserName());
                syncParam.setAccessToken(token.getAccessToken());
                tbOrderService.syncOrder(syncParam);
                **/
                //modify by liuqi 2021-3-18  新版的插入到redis生产者队列中
                token.setBeginTime((long)runTime);
                token.setEndTime((long)now);
                //对象转成JSON字符串，保存到redis队列中
                String alimmTokensStr =  JSONObject.toJSONString(token);
                redisTemplate.opsForList().leftPush(CacheKey.tbPayOrderQueue, alimmTokensStr);
            }
        }

        String val = sysSettingMapper.getByKey("pdd_heartbeat");
        int ht = Integer.parseInt(val);
        if (ht<lasttime){
            content = content + ",拼多多:["+ht+"]";
            PddOrderSyncParam syncParam = new PddOrderSyncParam();
            syncParam.setBegin_time((long)runTime);
            syncParam.setEnd_time((long)now);
            pddOrderService.syncOrder(syncParam);
        }


        if (StringUtils.isNotBlank(content)){
            content = content+",未同步订单！";
            //emailService.sendMail("订单同步警告",content);
        }
    }
}
